//
//  ViewController.swift
//  FloatClock
//
//  Created by runbey_dev_ios on 2023/6/19.
//

import UIKit
import AVKit
import NetSpeed

class ViewController: UIViewController {
    
    let timerName = "timer"
    var playerLayer: AVPlayerLayer!
    var pictureController: AVPictureInPictureController!
    var clockView: ClockView! = ClockView()
    var clockShowView: TopShowView! = TopShowView()
    var styleIndex = 1000;
    var showStyle = 0;

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //网络检测
        NetSpeed.shared.delegate = self
        // 默认1秒回调一次
        NetSpeed.shared.begin()
        // 或者可以自定义回调间隔时间(单位: 秒)
        NetSpeed.shared.begin(duration: 2)
        // Do any additional setup after loading the view.
        if AVPictureInPictureController.isPictureInPictureSupported() { //判断是否支持画中画
            setupUI()
            countDown()
            initPlayer()
            initPictureContoller()
            do {
                try AVAudioSession.sharedInstance().setCategory(.playback)//设置支持后台播放
                try AVAudioSession.sharedInstance().setActive(true)//激活音视频
                
            } catch {
                print(error)
            }
        } else {
            //这里提示不支持
        }
    }
    
    //加载UI
    func setupUI() {
        
        clockShowView.layer.cornerRadius = 100
        clockShowView.backgroundColor = UIColor.white
        clockShowView.layer.borderColor = UIColor.red.cgColor
        clockShowView.layer.borderWidth = 3
        clockShowView.layer.shadowRadius = 100;
        clockView.layer.shadowColor = UIColor.colorWithHexString("#333333").cgColor
        clockView.layer.shadowOpacity = 1
        clockView.layer.shadowOffset = CGSize(width: 20, height: 20)
        view.addSubview(clockShowView);
        let gesture = UITapGestureRecognizer(target: self, action: #selector(showStyleChange))
        clockShowView.addGestureRecognizer(gesture)
        clockShowView.snp.remakeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(60)
            make.height.equalTo(200)
            make.width.equalTo(200)
        }
        
        let openCloseButton = UIButton(type: .system)
        openCloseButton.setTitleColor(UIColor.red, for: .normal)
        openCloseButton.setTitle("打开/关闭", for: .normal)
        openCloseButton.addTarget(self, action: #selector(openCloseButtonClicked), for: .touchUpInside)
        view.addSubview(openCloseButton)
        
        openCloseButton.snp.makeConstraints { make in
            make.top.equalTo(clockShowView.snp.bottom).offset(20)
            make.centerX.equalToSuperview()
            make.width.equalTo(200)
            make.height.equalTo(40)
        }
        
        let changeButton = UIButton(type: .system)
        changeButton.setTitleColor(UIColor.red, for: .normal)
        view.addSubview(changeButton)
        changeButton.setTitle("秒/毫秒", for: .normal)
        changeButton.addTarget(self, action: #selector(millisecondButtonClicked), for: .touchUpInside)
        
        changeButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.height.equalTo(openCloseButton)
            make.top.equalTo(openCloseButton.snp.bottom).offset(20)
        }
        
        let colorStyle = UILabel()
        colorStyle.text = "更改悬浮背景色:";
        colorStyle.textColor = .red
        colorStyle.font = UIFont.systemFont(ofSize: 14.0);
        view.addSubview(colorStyle)
        colorStyle.snp.makeConstraints { make in
            make.top.equalTo(changeButton.snp.bottom).offset(20)
            make.left.equalTo(20)
            make.height.equalTo(40)
        }
        
        let grayButton = UIButton(type: .custom)
        grayButton.backgroundColor = .gray
        grayButton.layer.borderWidth = 4
        grayButton.layer.borderColor = UIColor.red.cgColor
        grayButton.tag = 100;
        view.addSubview(grayButton)
        grayButton.addTarget(self, action: #selector(backgroundColorChange), for: .touchUpInside)
        
        grayButton.snp.makeConstraints { make in
            make.centerY.equalTo(colorStyle)
            make.width.height.equalTo(30)
            make.left.equalTo(colorStyle.snp.right).offset(30)
        }
        
        let blueButton = UIButton(type: .custom)
        blueButton.backgroundColor = UIColor.colorWithHexString("#4CA2EB")
        blueButton.layer.borderWidth = 4
        blueButton.layer.borderColor = UIColor.white.cgColor
        blueButton.tag = 101;
        view.addSubview(blueButton)
        blueButton.addTarget(self, action: #selector(backgroundColorChange), for: .touchUpInside)
        
        blueButton.snp.makeConstraints { make in
            make.centerY.equalTo(colorStyle)
            make.width.height.equalTo(30)
            make.left.equalTo(grayButton.snp.right).offset(30)
        }
        
        let greenButton = UIButton(type: .custom)
        greenButton.backgroundColor = UIColor.colorWithHexString("#66DC79")
        greenButton.layer.borderWidth = 4
        greenButton.layer.borderColor = UIColor.white.cgColor
        greenButton.tag = 102;
        view.addSubview(greenButton)
        greenButton.addTarget(self, action: #selector(backgroundColorChange), for: .touchUpInside)
        
        greenButton.snp.makeConstraints { make in
            make.centerY.equalTo(colorStyle)
            make.width.height.equalTo(30)
            make.left.equalTo(blueButton.snp.right).offset(30)
        }
        
        let showStyle = UILabel()
        showStyle.text = "更改悬浮样式:";
        showStyle.textColor = .red
        showStyle.font = UIFont.systemFont(ofSize: 14.0);
        view.addSubview(showStyle)
        showStyle.snp.makeConstraints { make in
            make.top.equalTo(colorStyle.snp.bottom).offset(35)
            make.left.equalTo(20)
            make.height.equalTo(40)
        }
        
        let styleButtonOne = UIButton(type: .custom)
        styleButtonOne.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        styleButtonOne.setTitle("样式一", for: .normal)
        styleButtonOne.setTitleColor(UIColor.blue, for: .normal)
        styleButtonOne.layer.borderWidth = 4
        styleButtonOne.layer.borderColor = UIColor.red.cgColor;
        styleButtonOne.tag = 1000
        view.addSubview(styleButtonOne)
        styleButtonOne.addTarget(self, action: #selector(styleChange), for: .touchUpInside)
        
        styleButtonOne.snp.makeConstraints { make in
            make.width.equalTo(80)
            make.centerY.equalTo(showStyle)
            make.left.equalTo(showStyle.snp.right).offset(30)
        }
        
        let styleButtonTwo = UIButton(type: .custom)
        styleButtonTwo.setTitle("样式二", for: .normal)
        styleButtonTwo.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        styleButtonTwo.setTitleColor(UIColor.blue, for: .normal)
        styleButtonTwo.layer.borderWidth = 4
        styleButtonTwo.layer.borderColor = UIColor.white.cgColor;
        styleButtonTwo.tag = 1001
        view.addSubview(styleButtonTwo)
        styleButtonTwo.addTarget(self, action: #selector(styleChange), for: .touchUpInside)
        
        styleButtonTwo.snp.makeConstraints { make in
            make.width.equalTo(80)
            make.centerY.equalTo(showStyle)
            make.left.equalTo(styleButtonOne.snp.right).offset(30)
        }
    }
   
    //初始化AVPlayerLayer
    func initPlayer() {
        playerLayer = AVPlayerLayer()
        playerLayer.frame = .init(x: UIScreen.main.bounds.size.width/2, y: 60+100, width: 0.5, height: 0.5)
        clockView.frame = CGRect(x: 0, y: 0, width: playerLayer.frame.size.width, height: 200)
        //设置一个视频背景资源用于画中画
        let resources = Bundle.main.url(forResource: "beijing", withExtension: "MP4")
        let asset = AVAsset.init(url: resources!)
        let playerItem = AVPlayerItem.init(asset: asset)
        let player = AVPlayer.init(playerItem: playerItem)
        playerLayer.player = player
        playerLayer.isHidden = true
        //设置静音
        player.isMuted = true
        view.layer.addSublayer(playerLayer)
    }
    
    //初始化画中画
    func initPictureContoller() {
        pictureController = AVPictureInPictureController.init(playerLayer: playerLayer)!
        pictureController.delegate = self
        //设置画中画的样式 不包含其他按钮
        //0 默认样式 1不包含前进快退键 2 全部不包含 3加载显示类
        pictureController.setValue(2, forKey: "controlsStyle")
        
    }
    
    
    @objc private func showStyleChange() {
        showStyle+=1
        showStyle = showStyle%3
        clockShowView.showStyle = showStyle%3
        clockView.displayStyle = showStyle;
    }
    
    @objc func openCloseButtonClicked() {
        if pictureController.isPictureInPictureActive {
            //开启画中画
            pictureController.stopPictureInPicture()
        } else {
            //关闭画中画
            pictureController.startPictureInPicture()
        }
    }
    
    // 显示/隐藏 毫秒
    @objc private func millisecondButtonClicked() {
        clockView.isShowMilsecond = !clockView.isShowMilsecond
    }
    
    
    //改变悬浮背景色
    @objc private func backgroundColorChange(btn:UIButton) {
        for button in self.view.subviews {
            if (button.tag != btn.tag && button.tag >= 100 && button.tag<=102) {
                button.layer.borderColor = UIColor.white.cgColor;
            }
        }
        btn.layer.borderColor = UIColor.red.cgColor;
        switch btn.tag {
        case 100: self.clockView.backgroundColor = .gray
        case 101: self.clockView.backgroundColor = UIColor.colorWithHexString("#4CA2EB")
        case 102: self.clockView.backgroundColor = UIColor.colorWithHexString("#66DC79")
        default:
            break
        }
    }
    
    //改变悬浮样式
    @objc private func styleChange(btn:UIButton) {
        if (self.styleIndex == btn.tag) {
            return;
        }
        self.styleIndex = btn.tag;
        //停止画中画
        pictureController.stopPictureInPicture()
        for button in self.view.subviews {
            if (button.tag != btn.tag && button.tag >= 1000 && button.tag<=1001) {
                button.layer.borderColor = UIColor.white.cgColor;
            }
        }
        btn.layer.borderColor = UIColor.red.cgColor;
        self.clockView.showStyle = btn.tag - 1000;
        if (btn.tag == 1000) {
            let asset = AVAsset.init(url: Bundle.main.url(forResource: "beijing", withExtension: "MP4")!)
            let playerItem = AVPlayerItem.init(asset: asset)
            let player = AVPlayer.init(playerItem: playerItem)
            playerLayer.player = player
        } else {
            
            let asset = AVAsset.init(url: Bundle.main.url(forResource: "beijing-3", withExtension: "mov")!)
            let playerItem = AVPlayerItem.init(asset: asset)
            let player = AVPlayer.init(playerItem: playerItem)
            playerLayer.player = player
        }
        
        self.perform(#selector(openCloseButtonClicked), with: nil, afterDelay: 1);
    }
    
    //倒计时
    @objc private func countDown() {
        cancelTimer()
        MCGCDTimer.shared.scheduledDispatchTimer(WithTimerName: timerName, timeInterval: 0.034, queue: .global(), repeats: true) {
            DispatchQueue.main.async {
                let timeInterval = Date().timeIntervalSince1970
                let date = Date.init(timeIntervalSince1970: timeInterval)
                let dateFormat = DateFormatter()
                if self.clockView.isShowMilsecond {
                    dateFormat.dateFormat = "HH:mm:ss.SSS"
                } else {
                    dateFormat.dateFormat = "HH:mm:ss"
                }
                let dateString = dateFormat.string(from: date)
                self.clockView.timeLabel.text = dateString
                self.clockShowView.showLabel.text = dateString
            }
        }
    }
    
    func cancelTimer() {
        if MCGCDTimer.shared.isExistTimer(WithTimerName: timerName) {
            MCGCDTimer.shared.cancleTimer(WithTimerName: timerName)
        }
    }
}

extension ViewController : AVPictureInPictureControllerDelegate {
    
    //开启画中画的时候加载计数
    func pictureInPictureControllerWillStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
        let window = UIApplication.shared.windows.first
        window?.addSubview(clockView)
        clockView.snp.makeConstraints { (make) -> Void in
            make.edges.equalToSuperview()
        }
    }
    
    func pictureInPictureControllerWillStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
       
    }
    
    func pictureInPictureControllerDidStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
        
    }
}

extension ViewController: NetSpeedProtocol {
    
    func didSent(octets: UInt32) {
        let upload = "上行：\(formatSpeed(octets: octets))"
        self.clockView.netUpSpeedLabel.text = upload

    }
    
    func didReceived(octets: UInt32) {
        let download = "下行：\(formatSpeed(octets: octets))"
        self.clockView.netDownSpeedLabel.text = download
    }
    
    /// 格式化
    private func formatSpeed(octets: UInt32) -> String {
        var speedString = ""
        if octets >= 1024 * 1024 {
            speedString = String(format: "%lluMB/S", octets / (1024*1024))
        } else {
            speedString = String(format: "%lluKB/S", octets / 1024)
        }
        return speedString
    }
}
